#include "thread.h"

#include <pthread.h>
#include <cstdio>
#include <sys/prctl.h>
#include "latch.h"

using namespace tiny_muduo;

static void* ThreadRun(void* arg) {
	ThreadData* ptr = static_cast<ThreadData*>(arg);
    char thread_name[16];  
    snprintf(thread_name, sizeof(thread_name), "webserver_%d", ptr->thread_cnt_);

    // 设置线程名称
    pthread_setname_np(::pthread_self(), thread_name);
	ptr->RunOneFunc();
	delete ptr;
	return nullptr;
}

Thread::Thread(const ThreadFunc& func)
    : pthread_id_(-1),
      func_(func),
      latch_(1) {
}

Thread::~Thread() {
	::pthread_detach(pthread_id_);
}

void Thread::StartThread(int thread_cnt) {
	ThreadData* ptr = new ThreadData(func_, &latch_, thread_cnt);
	::pthread_create(&pthread_id_, nullptr, ThreadRun, ptr);
	latch_.Wait();
}
